import {
	HOME_ARTICLE_PARAMS,
	HOME_ARTICLE_CATEGORY,
	HOME_ARTICLE_DEL_PARAMS
} from "../constant";

const articleInitState = {
    // 文章列表搜索
    homeSearch: {
        page: 1,           // 页码
        size: 10,          // 页大小
        categoryId: 0,    // 分类ID
	    categoryName: '',
        tags: '',          // 标签
        time: ''           // 时间
    },
	// 文章分类信息
	categoryList: []
}

export default function articleReducer(state = articleInitState, action) {
    const {type, data} = action
    switch (type) {
	    case HOME_ARTICLE_DEL_PARAMS:
	    	return deleteSearch(state, data)
	    case HOME_ARTICLE_CATEGORY:
	    	console.log(state)
	    	return {
	    		...state,
			    categoryList: data
		    }
	    case HOME_ARTICLE_PARAMS:
	    	return updateSearch(state, data)
        default:
            return state
    }
}


function updateSearch(state, data) {
	// debugger;
	let homeSearch = Object.assign({}, state.homeSearch)
	const {value, field} = data
	if (field === 'categoryId') {
		const {categoryList} = state
		let idx = categoryList.find(item => item.id === data.value);
		if (idx !== undefined) {
			homeSearch.categoryName = idx.title
		}
	}
	homeSearch[field] = value
	return {
		...state,
		homeSearch
	}
}

/**
 * 删除查询属性
 * @param state
 * @param data
 */
function deleteSearch(state, data) {
	// debugger
	let homeSearch = Object.assign({}, state.homeSearch)
	const {field} = data
	switch (field) {
		case "categoryId":
			homeSearch.categoryId = 0
			homeSearch.categoryName = ''
			break
		case "tags":
			homeSearch.tags = ''
			break
		case "time":
			homeSearch.time = ''
			break
		default:
			break
	}
	return {
		...state,
		homeSearch
	}
}


